<?php

require_once (dirname(__FILE__) . '/../prepend.php');
global $bdd;
global $logger;
/*
 * Sepa Customer Credit Transfert
 * Génération de fichier SEPA virement pour les factures ponctuelles avoir
 * @author: Arthur
 */

use Digitick\Sepa;
if ($_SESSION['niveauAuth']<>'0'){
require_once("dao/FacturePonctuelleDao.php");


// Create the initiating information
$groupHeader = new Sepa\GroupHeader('SEPA-' . time(), PRESTATAIRE_NOM);
$sepaFile = new Sepa\TransferFile\CustomerCreditTransferFile($groupHeader);

// Create a PaymentInformation the Transfer belongs to
$payment = new Sepa\PaymentInformation(
        'SEPA-' . time(), // identifier
        IBAN, // IBAN the money is transferred from
        BIC, // BIC
        PRESTATAIRE_NOM // Debitor Name
);

//liste les avoirs
$avoirs = FacturePonctuelleDao::getAvoirsForSepa();

if (empty($avoirs)) {
    $alert = array('message' => 'Aucun avoir à ajouter au fichier SEPA', 'type' => 'warning');
    $_SESSION['alerts'][] = $alert;
    return redirect("../../lancement-facture");
}

foreach ($avoirs as $avoir) {
    $totalTTC = round( (float) $avoir->prixHT * 1.2, 2 );
    //remplace caractères spéciaux
    $clientName = str_replace('&', 'et', $avoir->client->raison_social);
    // création de l'iban en retirant les espaces
    $iban = trim($avoir->client->code_iban) . trim($avoir->client->code_etablissement) . trim($avoir->client->code_guichet) . trim($avoir->client->num_compte) . trim($avoir->client->rib);

    $transfer = new Sepa\TransferInformation\CustomerCreditTransferInformation(
            $totalTTC, // Amount
            $iban, //IBAN of creditor
            $avoir->client->code_client_hto //Name of Creditor
    );
    $transfer->setBic($avoir->client->swift); // Set the BIC explicitly
    $transfer->setRemittanceInformation("Avoir " . date("Y-m-d"));

    // It's possible to add multiple Transfers in one Payment
    $payment->addTransfer($transfer);
    $return[] = $avoir->id;
}

// It's possible to add multiple payments to one SEPA File
$sepaFile->addPaymentInformation($payment);

// Attach a dombuilder to the sepaFile to create the XML output
$domBuilder = Sepa\DomBuilder\DomBuilderFactory::createDomBuilder($sepaFile, 'pain.001.001.03');

//MAJ factures
$q = 'UPDATE factures_ponctuelles SET sepa = TRUE WHERE id IN (' . implode(', ', $return) . ');';
$requete = $bdd->prepare($q);
$requete->execute();

// Or if you want to use the format 'pain.001.001.03' instead
// $domBuilder = DomBuilderFactory::createDomBuilder($sepaFile, 'pain.001.001.03');
header('Content-type: text/xml');
header('Content-Disposition: attachment; filename=' . date("Ymd") . '-SEPA.xml');
echo $domBuilder->asXml();
}
else {
redirect("home-admin");
}
